  <template>
    <div class="app-container">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


        <el-form-item label="药品名称" prop="drugName">
          <el-select
            v-model="queryParams.drugName"
            placeholder="请选择药品名称"
            clearable
            filterable
            @keyup.enter.native="handleQuery">
            <el-option
              v-for="item in drugList"
              :key="item.drugId"
              :label="item.drugName"
              :value="item.drugName">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="总金额" prop="totalAmount">
          <el-input
            v-model="queryParams.totalAmount"
            placeholder="请输入总金额"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['patient_drug:patient_drug:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['patient_drug:patient_drug:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['patient_drug:patient_drug:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['patient_drug:patient_drug:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="patient_drugList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="药单序号" align="center" prop="takeId" />
        <el-table-column label="患者姓名" align="center" prop="patientName" />
        <el-table-column label="药房ID" align="center" prop="pharmacyName" />
  <!--      <el-table-column label="药品ID" align="center" prop="drugId" />-->
        <el-table-column label="药品名称" align="center" prop="drugName" />
        <el-table-column label="取药数量" align="center" prop="quantity" />
        <el-table-column label="总金额" align="center" prop="totalAmount" />
        <el-table-column label="时间" align="center" prop="takeTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.takeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['patient_drug:patient_drug:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['patient_drug:patient_drug:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 新增/修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="患者姓名" prop="patientName">
            <el-input v-model="form.patientName" placeholder="请输入患者姓名" style="width: 200px" />
          </el-form-item>

          <el-form-item label="药房ID" prop="pharmacyId">
            <el-select v-model="form.pharmacyId" placeholder="请选择药房ID" clearable>
              <el-option
                v-for="item in pharmacyList"
                :key="item.pharmacyId"
                :label="item.pharmacyName"
                :value="item.pharmacyId">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 药品名称选择（联动药品ID） -->
          <el-form-item label="药品名称" prop="drugName">
            <el-select
              v-model="form.drugName"
              placeholder="请选择药品名称"
              clearable
              @change="handleDrugNameChange">
              <el-option
                v-for="item in drugList"
                :key="item.drugId"
                :label="item.drugName"
                :value="item.drugName">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 药品ID（自动填充，只读） -->
          <el-form-item label="药品ID" prop="drugId">
            <el-input
              v-model="form.drugId"
              placeholder="选择药品名称后自动生成"
              readonly
              disabled>
            </el-input>
          </el-form-item>

          <el-form-item label="取药数量" prop="quantity">
            <el-input v-model="form.quantity" placeholder="请输入取药数量" style="width: 200px" @input="calcTotalAmount"  @change="checkStock"
            />
            <!-- 新增：显示当前库存 -->
            <span style="margin-left: 10px;">当前库存：{{ currentStock }}</span>
          </el-form-item>
          <el-form-item label="总金额" prop="totalAmount">
            <el-input v-model="form.totalAmount" placeholder="请输入总金额" style="width: 200px" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <!--整合时只需要修改路径-->
  <script>
  import { listPatient_drug, getPatient_drug, delPatient_drug, addPatient_drug, updatePatient_drug } from "@/api/patient_drug/patient_drug"
  import { listManagement } from "@/api/BasicSettings/management" // 假设有这个API
  import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy.js"
  import { listPharmacyStock } from "@/api/pharmacy/pharmacyStock";

  export default {
    name: "Patient_drug",
    mixins: [drugAndPharmacy],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 病人取药表格数据
        patient_drugList: [],
        // 药品列表数据（用于下拉选择）
        drugList: [],
        // 药房列表数据（用于下拉选择）
        pharmacyList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          patientName: null,
          drugName: null,
          totalAmount: null,
        },
        // 表单参数
        form: {
          takeId: null,
          patientName: null,
          pharmacyId: null,
          drugId: null,
          drugName: null,
          quantity: null,
          totalAmount: null,
          takeTime: null,
          remark: null
        },
        // 表单校验规则
        rules: {
          patientName: [
            { required: true, message: "患者姓名不能为空", trigger: "blur" }
          ],
          pharmacyId: [
            { required: true, message: "药房ID不能为空", trigger: "blur" }
          ],
          drugName: [
            { required: true, message: "药品名称不能为空", trigger: ["blur", "change"] }
          ],
          drugId: [
            { required: true, message: "药品ID不能为空", trigger: "blur" }
          ],
          quantity: [
            { required: true, message: "取药数量不能为空", trigger: "blur" }
          ],
          totalAmount: [
            { required: true, message: "总金额不能为空", trigger: "blur" }
          ],
        },
        currentStock: 0, // 新增：存储当前库存
        drugPrice: 0, // 新增：存储当前选中药品的单价
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询病人取药列表 */
      getList() {
        this.loading = true
        listPatient_drug(this.queryParams).then(response => {
          this.patient_drugList = response.rows
          this.total = response.total
          this.loading = false
        })
      },

      /** 选择药品名称后自动填充药品ID */
      handleDrugNameChange(selectedDrugName) {
        // 清空选择时同步清空ID
        if (!selectedDrugName) {
          this.form.drugId = null
          this.currentStock = 0
          this.drugPrice = 0; // 清空单价
          return
        }

        // 根据选择的药品名称匹配对应的ID
        const matchedDrug = this.drugList.find(item => item.drugName === selectedDrugName)
        if (matchedDrug) {
          this.form.drugId = matchedDrug.drugId
          this.drugPrice = matchedDrug.price; // 赋值药品单价
          // 调用库存查询
          this.queryCurrentDrugStock()
          //触发计算总金额（若数量已填）
          this.calcTotalAmount();
        } else {
          this.form.drugId = null
          this.currentStock = 0
          this.$message.warning("未找到对应的药品信息")
          this.drugPrice = 0; // 清空单价
        }
      },

      /** 查询当前库存的方法 */
      async queryCurrentDrugStock() {
        // 先调用全量库存接口
        const res = await listPharmacyStock({ pageNum: 1, pageSize: 10000 });
        const stockList = res.rows;
        // 从全量列表里筛选：药房ID和药品ID都匹配的那条数据
        const targetStock = stockList.find(item =>
          item.pharmacyId === this.form.pharmacyId &&
          item.drugId === this.form.drugId
        );
        if (targetStock) {
          this.currentStock = targetStock.quantity; // 假设库存字段是 quantity
        } else {
          this.currentStock = 0; // 没找到
        }
      },
      // 计算总金额：数量 × 单价
      calcTotalAmount() {
        // 确保数量和单价有效
        if (this.form.quantity && this.drugPrice) {
          this.form.totalAmount = this.form.quantity * this.drugPrice;
        } else {
          this.form.totalAmount = null; // 清空无效计算
        }
      },
      //检查数量
      checkStock() {
        if (this.form.quantity > this.currentStock) {
          this.$message.warning(`取药数量不能超过库存！当前库存为 ${this.currentStock}`);
          this.form.quantity = null; // 可选：清空输入框，强制用户重新输入
        }
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },

      // 表单重置
      reset() {
        this.form = {
          takeId: null,
          patientName: null,
          pharmacyId: null,
          drugId: null,
          drugName: null,
          quantity: null,
          totalAmount: null,
          takeTime: null,
          remark: null
        }
        this.currentStock = 0
        this.drugPrice = 0; // 清空药品单价
        this.resetForm("form")
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.takeId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加病人取药"
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const takeId = row.takeId || this.ids
        getPatient_drug(takeId).then(response => {
          this.form = response.data;
          // 回显药品单价（需从 drugList 匹配）
          const matchedDrug = this.drugList.find(
            (item) => item.drugName === this.form.drugName
          );
          if (matchedDrug) {
            this.drugPrice = matchedDrug.price;
          }
          // 回显库存
          this.queryCurrentDrugStock()
          this.form = response.data
          this.open = true
          this.title = "修改病人取药"
        })
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.takeId != null) {
              updatePatient_drug(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addPatient_drug(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const takeIds = row.takeId || this.ids
        this.$modal.confirm(`是否确认删除病人取药编号为"${takeIds}"的数据项？`).then(() => {
          return delPatient_drug(takeIds)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('patient_drug/patient_drug/export', {
          ...this.queryParams
        }, `patient_drug_${new Date().getTime()}.xlsx`)
      }
    }
  }
  </script>
